<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-tabs v-model="activeTab" type="border-card">
			<el-tab-pane label="调休单详情" name="main">
				<el-card shadow="hover" class="layout-padding-auto create-form">
					<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>单据信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_BillCode_FormItem" prop="Entity.BillCode">
										<template #label>
											<WtmLabelTooltip label="单据编号" tooltip="单据编号" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.BillCode" class="width100" disabled></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_BillStatus_FormItem" prop="Entity.BillStatus">
										<template #label>
											<WtmLabelTooltip label="单据状态" tooltip="单据状态" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.BillStatus" class="width100" disabled>
											<el-option key="草稿" value="草稿" label="草稿"></el-option>
											<el-option key="正文" value="正文" label="正文"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_WorkflowStatus_FormItem" prop="Entity.WorkflowStatus">
										<template #label>
											<WtmLabelTooltip label="工作流状态" tooltip="工作流状态" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.WorkflowStatus" class="width100" disabled>
											<el-option key="待提交" value="待提交" label="待提交"></el-option>
											<el-option key="提交中" value="提交中" label="提交中"></el-option>
											<el-option key="审核中" value="审核中" label="审核中"></el-option>
											<el-option key="已完成" value="已完成" label="已完成"></el-option>
											<el-option key="已取消" value="已取消" label="已取消"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
										<template #label>
											<WtmLabelTooltip label="备注" tooltip="备注" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Remark" class="width100" disabled></el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>基本信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_PersonId_FormItem" prop="Entity.PersonId">
										<template #label>
											<WtmLabelTooltip label="员工" tooltip="关联的员工实体" />
										</template>
										<WtmPersonSelector v-model="stateData.vmModel.Entity.PersonId" :prefill-person="prefillPerson" :disabled="true" />
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_StaffNo_FormItem" prop="Entity.StaffNo">
										<template #label>
											<WtmLabelTooltip label="员工工号" tooltip="员工工号" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.StaffNo" class="width100" disabled></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name">
										<template #label>
											<WtmLabelTooltip label="员工姓名" tooltip="员工姓名" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Name" class="width100" disabled></el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>调休申请信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_StartTime_FormItem" prop="Entity.StartTime">
										<template #label>
											<WtmLabelTooltip label="开始时间" tooltip="开始时间" />
										</template>
										<el-date-picker v-model="stateData.vmModel.Entity.StartTime" type="date" class="width100" disabled></el-date-picker>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_EndTime_FormItem" prop="Entity.EndTime">
										<template #label>
											<WtmLabelTooltip label="结束时间" tooltip="结束时间" />
										</template>
										<el-date-picker v-model="stateData.vmModel.Entity.EndTime" type="date" class="width100" disabled></el-date-picker>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Days_FormItem" prop="Entity.Days">
										<template #label>
											<WtmLabelTooltip label="天数" tooltip="天数" />
										</template>
										<el-input-number v-model="stateData.vmModel.Entity.Days" class="width100" disabled></el-input-number>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_CompOffType_FormItem" prop="Entity.CompOffType">
										<template #label>
											<WtmLabelTooltip label="调休类型" tooltip="正常调休/等时调休" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.CompOffType" class="width100" disabled>
											<el-option key="正常调休" value="正常调休" label="正常调休"></el-option>
											<el-option key="等时调休" value="等时调休" label="等时调休"></el-option>
											<el-option key="积分兑换" value="积分兑换" label="积分兑换"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="24" class="mb20" v-if="stateData.vmModel.Entity.CompOffType === '等时调休'">
									<el-form-item ref="Entity_AvailableOvertime_FormItem" prop="Entity.AvailableOvertime">
										<template #label>
											<WtmLabelTooltip label="已使用加班记录" tooltip="本次调休使用的加班记录及时长" />
										</template>
										<WtmTable
											ref="overtimeTableRef"
											:data="overtimeTableData.data"
											:header="overtimeTableData.header"
											:config="overtimeTableData.config"
										/>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20" v-if="stateData.vmModel.Entity.CompOffType === '等时调休'">
									<el-form-item ref="Entity_CompOffHours_FormItem" prop="Entity.CompOffHours">
										<template #label>
											<WtmLabelTooltip label="调休时长(小时)" tooltip="等时调休使用的小时数" />
										</template>
										<el-input-number v-model="stateData.vmModel.Entity.CompOffHours" class="width100" disabled></el-input-number>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Reason_FormItem" prop="Entity.Reason">
										<template #label>
											<WtmLabelTooltip label="调休事由" tooltip="调休事由" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Reason" type="textarea" :rows="2" class="width100" disabled></el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>工作信息</span>
							</div>
							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<WtmOrgSelector v-model="stateData.vmModel.Entity.OrgId" label="公司" prop="Entity.OrgId" :auth="false" :disabled="true" />
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<WtmDeptSelector v-model="stateData.vmModel.Entity.GroupId" prop="Entity.GroupId" label="所属部门" :auth="false" :disabled="true" />
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>审批信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Approver_FormItem" prop="Entity.Approver">
										<template #label>
											<WtmLabelTooltip label="审批人" tooltip="流程审批人" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Approver" class="width100" disabled></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_ApprovalTime_FormItem" prop="Entity.ApprovalTime">
										<template #label>
											<WtmLabelTooltip label="审批时间" tooltip="流程审批时间" />
										</template>
										<el-date-picker v-model="stateData.vmModel.Entity.ApprovalTime" type="datetime" class="width100" disabled></el-date-picker>
									</el-form-item>
								</el-col>
							</el-row>
						</div>
					</el-form>
				</el-card>
			</el-tab-pane>

			<el-tab-pane label="审批流程" name="workflow">
				<WtmWorkflowTimeline entityType="HengTong.Areas.Daily.Controllers.SysDailyCompOffRequestBill" :entityId="stateData.vmModel.Entity.ID" />
			</el-tab-pane>
		</el-tabs>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.details;false">
import { reactive, ref, getCurrentInstance, onMounted, nextTick, type ComponentInternalInstance, computed } from 'vue';
import { SysDailyCompOffRequestBillApi as api } from '/@/views/daily/sysdailycompoffrequestbill/api';
import other from '/@/utils/other';
import { ISysDailyCompOffRequestBillVm } from '/@/views/daily/sysdailycompoffrequestbill/api/interface';
import { IViewModel } from '/@/types/common';
import ApproveReasonDialog from '/@/components/approveReason/index.vue';

const ACTIONS = {
	AGREE: '同意',
	REJECT: '拒绝',
} as const;

const BUTTON_TEXTS = {
	AGREE: '同意',
	REJECT: '拒绝',
	CLOSE: '关闭',
} as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const activeTab = ref('main');
const overtimeTableRef = ref();

// 加班记录表格配置（只读模式）
const overtimeTableData = ref<any>({
	data: [] as any[],
	header: [
		{ title: '加班单号', key: 'BillCode', type: 'text', isCheck: true, width: '140' },
		{ title: '补偿类型', key: 'CompensationType', type: 'text', isCheck: true, width: '100' },
		{ title: '姓名', key: 'Name', type: 'text', isCheck: true, width: '100' },
		{ title: '工号', key: 'StaffNo', type: 'text', isCheck: true, width: '100' },
		{ title: '开始时间', key: 'StartTime', type: 'datetime', isCheck: true, width: '150' },
		{ title: '结束时间', key: 'EndTime', type: 'datetime', isCheck: true, width: '150' },
		{ title: '加班时长(小时)', key: 'OvertimeHours', type: 'text', isCheck: true, width: '120', fixed: 'right' },
		{ title: '本次使用时长(小时)', key: 'UsedCompOffHours', type: 'text', isCheck: true, width: '140', fixed: 'right' },
		{ title: '剩余可用时长(小时)', key: 'RemainingCompOffHours', type: 'text', isCheck: true, width: '140', fixed: 'right' },
		{ title: '事由', key: 'Reason', type: 'text', isCheck: true, width: '200' },
	],
	config: {
		total: 0,
		loading: false,
		isSerialNo: false,
		isSelection: false, // 详情页不需要勾选
		isOperate: false,
		isBorder: true,
		hideSetting: true,
		hidePrint: true,
		hideRefresh: true,
		hideDensity: true,
	},
});

const stateData = reactive<IViewModel<ISysDailyCompOffRequestBillVm>>({
	vmModel: {
		Entity: {
			ID: null,
			PersonId: null,
			OrgId: null,
			StaffNo: null,
			Name: null,
			StartTime: null,
			EndTime: null,
			Days: null,
			Reason: null,
			CompOffType: null,
			CompOffHours: null,
			CompOffOvertimeLinks: [], // 添加这个字段的初始化
			Approver: null,
			ApprovalTime: null,
			GroupId: null,
			BillCode: null,
			BillStatus: null,
			WorkflowStatus: null,
			Remark: null,
		} as any,
		SelectedCompOffOvertimeLinksIds: [],
		ActionName: null,
		IsMyApprove: null,
		Remark: null,
	},
	AllSysGroups: [] as any[],
	AllSysDailyOvertimeRequestBills: [] as any[],
});

// 预填充人员信息（用于WtmPersonSelector回显）
const prefillPerson = computed(() => {
	if (stateData.vmModel.Entity.PersonId && stateData.vmModel.Entity.Name) {
		return {
			ID: stateData.vmModel.Entity.PersonId,
			Name: stateData.vmModel.Entity.Name,
			StaffNo: stateData.vmModel.Entity.StaffNo,
		};
	}
	return null;
});

const handleApiResponse = (response: any) => {
	loading.value = false;
	emit('refresh');
	closeDialog();
};

const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

const handleApproval = (actionName: string) => {
	stateData.vmModel.ActionName = actionName;
	loading.value = true;
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			api()
				.approve(stateData.vmModel, '')
				.then((res) => handleApiResponse(res))
				.catch(handleError);
		} else {
			loading.value = false;
		}
	});
};

const onAgree = () => {
	other.openDialog('填写同意原因', ApproveReasonDialog, null, null, '30%', (reason: string) => {
		stateData.vmModel.Remark = reason;
		handleApproval(ACTIONS.AGREE);
	});
};

const onDeny = () => {
	other.openDialog('填写拒绝原因', ApproveReasonDialog, { isRequired: true }, null, '30%', (reason: string) => {
		stateData.vmModel.Remark = reason;
		handleApproval(ACTIONS.REJECT);
	});
};

const onClose = () => {
	closeDialog();
};

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		(stateData.vmModel.Entity as any).ID = wtmdata.ID;
	}
};

// 加载已使用的加班记录
const loadUsedOvertimeRecords = async () => {
	if (!stateData.vmModel.Entity.PersonId) {
		return;
	}

	// 如果 CompOffOvertimeLinks 为空或不存在，说明没有使用加班记录
	const compOffLinks = stateData.vmModel.Entity.CompOffOvertimeLinks || [];
	if (compOffLinks.length === 0) {
		overtimeTableData.value.data = [];
		overtimeTableData.value.config.total = 0;
		return;
	}

	overtimeTableData.value.config.loading = true;
	try {
		// 详情页传递调休单 ID，让后端返回包含已使用的加班记录
		const response = await api().getAvailableOvertimeForCompOff(stateData.vmModel.Entity.PersonId as string, stateData.vmModel.Entity.ID as string);
		const allRecords = response.Data || response.data || [];

		// 创建一个 Map 来快速查找已使用的加班记录
		const usedOvertimeMap = new Map<string, number>();
		compOffLinks.forEach((link: any) => {
			// 后端可能返回 HoursUsed 或 UsedHours，兼容两种情况
			const usedHours = link.HoursUsed || link.UsedHours || 0;
			usedOvertimeMap.set(link.OvertimeRequestBillId, usedHours);
		});

		// 只显示已使用的加班记录
		overtimeTableData.value.data = allRecords
			.filter((record: any) => usedOvertimeMap.has(record.ID))
			.map((record: any) => ({
				...record,
				UsedCompOffHours: usedOvertimeMap.get(record.ID) || 0,
			}));

		overtimeTableData.value.config.total = overtimeTableData.value.data.length;
	} catch (error) {
		console.error('加载已使用加班记录失败:', error);
	} finally {
		overtimeTableData.value.config.loading = false;
	}
};

// 加载页面数据
const loadPageData = async () => {
	const API_ENDPOINTS = {
		GROUPS: '/api/SysDailyCompOffRequestBill/GetSysGroups',
		OVERTIME_BILLS: '/api/SysDailyCompOffRequestBill/GetSysDailyOvertimeRequestBills',
	} as const;

	const [groups, overtimeBills, entityData] = await Promise.allSettled([
		other.getSelectList(API_ENDPOINTS.GROUPS, [], false),
		other.getSelectList(API_ENDPOINTS.OVERTIME_BILLS, [], false),
		api().get(stateData.vmModel.Entity.ID ?? ''),
	]);

	// 处理成功的结果
	if (groups.status === 'fulfilled') stateData.AllSysGroups = groups.value;
	if (overtimeBills.status === 'fulfilled') stateData.AllSysDailyOvertimeRequestBills = overtimeBills.value;
	if (entityData.status === 'fulfilled') {
		other.setValue(stateData.vmModel, entityData.value);

		// 如果是等时调休，加载已使用的加班记录
		if (stateData.vmModel.Entity.CompOffType === '等时调休' && stateData.vmModel.Entity.PersonId) {
			await loadUsedOvertimeRecords();
		}
	}
};

// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		await loadPageData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const canApprove = !!stateData.vmModel.IsMyApprove;

	const headerButtons = [
		{
			text: BUTTON_TEXTS.AGREE,
			type: 'primary',
			onClick: onAgree,
			visible: canApprove,
		},
		{
			text: BUTTON_TEXTS.REJECT,
			type: 'danger',
			onClick: onDeny,
			visible: canApprove,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];

	emit('updateHeaderButtons', headerButtons);
};
</script>
